package com.itheima.common.util;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
/***
 * @Author： shenkunlin
 * @Description: itheima-leadnews com.itheima.common.util
 * @Date 2021/6/22 : 3:23
 ****/
@Slf4j
public class AESUtil {

    /***
     * 加密
     * @param sSrc :明文
     * @param sKey :秘钥
     * @return
     * @throws Exception
     */
    public static String Encrypt(String sSrc, String sKey) throws Exception {
        if (validation(sKey)){
            return null;
        }
        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        //"算法/模式/补码方式"
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
        //此处使用BASE64做转码功能，同时能起到2次加密的作用。
        return new BASE64Encoder().encode(encrypted);
    }



    /***
     * 解密
     * @param sSrc :密文
     * @param sKey :秘钥
     * @return
     * @throws Exception
     */
    public static String Decrypt(String sSrc, String sKey) throws Exception {
        try {
            // 判断Key是否正确
            if (validation(sKey)){
                return null;
            }
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);//先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original,"utf-8");
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }

    /**
     * 参数校验
     * @param sKey
     * @return
     */
    private static boolean validation(String sKey) {
        if (sKey == null) {
            log.error("Key为空null");
            return true;
        }
        // 判断Key是否为16位
        if (sKey.length() != 16) {
            log.error("Key长度不是16位");
            return true;
        }
        return false;
    }
 
    public static void main(String[] args) throws Exception {
        //此处使用AES-128-ECB加密模式，key需要为16位。
        String cKey = "9439db3bdc084fc9";
        // 需要加密的字串
        String cSrc = "黑马头条";
        System.out.println(cSrc);
        // 加密
        String enString = AESUtil.Encrypt(cSrc, cKey);
        System.out.println("密文：" + enString);
 
        // 解密
        String DeString = AESUtil.Decrypt(enString, cKey);
        System.out.println("解密后明文：" + DeString);
    }
}